package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.LevelDto;
import com.zzyl.entity.Level;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.LevelMapper;
import com.zzyl.service.LevelService;
import com.zzyl.vo.LevelVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LevelServiceImpl implements LevelService {

    @Autowired
    private LevelMapper levelMapper;

    @Override
    public PageResponse<LevelVo> selectByPage(Integer pageNum, Integer pageSize, String name, Integer status) {
        PageHelper.startPage(pageNum, pageSize);
        Page<LevelVo> page = levelMapper.selectByPage(name, status);

        return PageResponse.of(page, LevelVo.class);
    }

    @Override
    public int addLevel(LevelDto levelDto) {
        if (levelDto != null) {
            Level level = BeanUtil.copyProperties(levelDto, Level.class);

            int row = levelMapper.countByName(level.getName());
            if (row > 0) {
                throw new BaseException(BasicEnum.INSERT_NURSINGLEVEL_FAIL);
            }
            row = levelMapper.selectByPlanId(level.getPlanId());
            if (row > 0) {
                throw new BaseException(BasicEnum.UPDATE_NURSINGLEVELPLAN_FAIL);
            }

            return levelMapper.insert(level);
        }
        return 0;
    }

    @Override
    public int updateLevel(LevelDto levelDto) {
        Level level = BeanUtil.copyProperties(levelDto, Level.class);
        String oldName = selectLevelById(level.getId()).getName();
        String name = level.getName();
        if (!name.equals(oldName)) {
            int row = levelMapper.countByName(name);
            if (row > 0) {
                throw new BaseException(BasicEnum.UPDATE_NURSINGLEVEL_FAIL);
            }
        }
        int row = levelMapper.selectByPlanId(level.getPlanId());
        if (row > 0) {
            throw new BaseException(BasicEnum.UPDATE_NURSINGLEVELPLAN_FAIL);
        }
        return levelMapper.updateById(level);
    }

    @Override
    public int deleteLevel(Integer id) {
        return levelMapper.deleteById(id);
    }

    @Override
    public LevelVo selectLevelById(Long id) {
        return levelMapper.selectById(id);
    }

    @Override
    public List<LevelVo> selectAll() {
        return levelMapper.selectAll();
    }

    @Override
    public int updateStatusById(Integer id, Integer status) {
        return levelMapper.updateStatusById(id, status);
    }

}
